#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){
  int npart, n;

  if ( argc != 4 ){
    fprintf(stderr, "Usage: avotosep <in-file> <out-file> <sigma>");
    exit(EXIT_FAILURE);
  }

  float sigma = atof(argv[3]);
 
  printf("%s and %s\n", argv[1], argv[2]);
  FILE *fin = fopen(argv[1], "r"); 
  FILE *fout = fopen(argv[2], "w");

  if ( fin==NULL || fout==NULL ){
    fprintf(stderr, "File error\n");
    exit(EXIT_FAILURE);
  }

  fscanf(fin, "%d\n", &npart);

  size_t size1 = npart*sizeof(float);
  size_t size2 = npart*sizeof(char);

  float *x = malloc(size1);
  float *y = malloc(size1);
  float *z = malloc(size1);
  char *t = malloc(size2);

  if ( x==NULL || y==NULL || z==NULL || t==NULL ){
    fprintf(stderr, "Allocation error");
    exit(EXIT_FAILURE);
  }

  fscanf(fin, "\n");
  
  float xcm = 0; float ycm = 0; float zcm = 0;
  for ( n=0; n<npart; n++){
    fscanf(fin, "%c %f %f %f\n", &t[n], &x[n], &y[n], &z[n]);

    xcm += x[n];
    ycm += y[n];
    zcm += z[n];
  }

  fclose(fin);

  xcm /= npart;
  ycm /= npart;
  zcm /= npart;


  for ( n=0; n<npart; n++){
    x[n] = (x[n] - xcm)/sigma;
    y[n] = (y[n] - ycm)/sigma;
    z[n] = (z[n] - zcm)/sigma;
  }

  fprintf(fout, "%d\n", npart);
  fprintf(fout, "Generated with avotosep. ABSOLUTELY NO WARRANTY\n");
  
  for ( n=0; n<npart; n++ )
    fprintf(fout, "%c %f %f %f\n", t[n], x[n], y[n], z[n]);

  fclose(fout);

  free(x); free(y); free(z); free(t);

  return 0;
}
